package com.xujianlun.cpms.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xujianlun.cpms.entity.sys.Menu;
import com.xujianlun.cpms.entity.sys.Role;
import com.xujianlun.cpms.entity.sys.RoleMenu;
import com.xujianlun.cpms.mapper.sys.RoleMapper;
import com.xujianlun.cpms.mapper.sys.RoleMenuMapper;
import com.xujianlun.cpms.service.sys.IMenuService;
import com.xujianlun.cpms.service.sys.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xujianlun
 * @since 2022-11-24
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private IMenuService menuService;

    @Transactional
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        //先删除当前角色ID所有绑定的关系
        QueryWrapper<RoleMenu> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("role_id",roleId);
        roleMenuMapper.delete(objectQueryWrapper);
        //再把前端传过来的菜单ID绑定到当前的这个角色ID上去

        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);//copy一个新的出来
        for (Integer menuId : menuIds) {
            Menu menu = menuService.getById(menuId);
            if (menu.getPid()!=null && !menuIdsCopy.contains(menu.getPid())){ //如果pid不是null，并且传过来的menuId数组里面没有父级id
                // 这他就是二级菜单  还要补上这个父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public List<Integer> getRoleMenuByRoleId(Integer roleId) {

        return roleMenuMapper.selectByRoleId(roleId);
    }
}
